package com.demo.ctf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class WhenCompleteDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
            return "Result of the async operation";
        });

        future.whenComplete((result, throwable) -> {
            if (throwable != null) {
                // 处理异步操作抛出的异常
                System.err.println("Async operation failed: " + throwable.getMessage());
            } else {
                // 处理异步操作的结果
                System.out.println("Async operation completed successfully with result: " + result);
            }
        });

        // 主线程等待异步任务完成
        future.get();
    }
}